package com.banshou.installs.model.net;

import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.RxFragment;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import io.reactivex.ObservableTransformer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by cjq on 2018/7/30.
 * Email: stoic_yb@139.com
 * features:切换线程，绑定生命周期
 */
public class RxUtil {

    private static <T> ObservableTransformer<T,T> schedulerTransformer(final Scheduler suberOn,final Scheduler obserOn,final boolean delayError){
        return observable -> observable.subscribeOn(suberOn).observeOn(obserOn,delayError);
    }

    /**
     * io -> main
     */
    public static <T> ObservableTransformer<T,T> io2main(){
        return schedulerTransformer(Schedulers.io(), AndroidSchedulers.mainThread(),false);
    }

    /**
     * activity
     */
    public static <T> ObservableTransformer<T,T> lifecycle(RxAppCompatActivity appCompatActivity){
        return obserable -> obserable.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).compose(appCompatActivity.bindUntilEvent(ActivityEvent.DESTROY));
    }

    /**
     * fragment
     */
    public static <T> ObservableTransformer<T,T> lifecycle(RxFragment fragment){
        return obserable -> obserable.compose(fragment.bindUntilEvent(FragmentEvent.DESTROY));
    }
}
